package com.paper.tiger.easy.rpc.s.client.registy.handler;

import com.paper.tiger.easy.rpc.core.RegisterData;
import com.paper.tiger.easy.rpc.core.ServerType;
import com.paper.tiger.easy.rpc.s.client.client.ContextManager;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * [简要描述]:
 * [详细描述]:
 *
 * @author ZouHaiBo
 * @version 1.0, 2021/6/16 15:01
 * @since JDK 1.8
 */
public class ClientHeartBeatHandler extends ChannelInboundHandlerAdapter
{

    private static Logger logger = LoggerFactory.getLogger(ClientHeartBeatHandler.class);

    /**
     * 客户端连接成功
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception
    {
        logger.info("client connetion success ，execute channelActive");

        // 执行定时任务，每隔5秒发送服务器心跳包

        RegisterData data = new RegisterData();
        data.setType(ServerType.HEART_BEAT_REQ.getCode());

        // 每隔5秒，向服务器发送一次心跳包
        ctx.executor().scheduleAtFixedRate(() ->
        {
            ctx.channel().writeAndFlush(data);

        }, 0, 5, TimeUnit.SECONDS);
        // 触发下一个
        ctx.fireChannelActive();

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception
    {
        logger.info("发生异常了，",cause);
        ContextManager.getInstance().setRegistyChannel(null);
        ctx.close();
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception
    {
        logger.info("服务端断开连接，客户端进行重连..");
        ContextManager.getInstance().doConnect();
    }


}
